import './TeacherTestList.scss';
import TestItem from './componets/TestItem/TestItem';
import { localGetTestListAPI } from '@/apis/student';
import { deletePartAPI, addPartAPI, changePartAPI } from '@/apis/teacher';
import { fetchGetPartList } from '@/store/modules/teacher';
import { useEffect, useState } from 'react';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Modal, ConfigProvider, Input, message, DatePicker } from 'antd';
import { useDispatch, useSelector } from 'react-redux';

export default function TeacherTestList() {
    const dispatch = useDispatch();
    const { user_status } = useSelector(state => state.user);
    const { partList } = useSelector(state => state.teacher);
    const [testArr, setTestArr] = useState([]);
    const [checkList, setCheckList] = useState([]);
    const [hasChecked, setHasChecked] = useState(false);
    const [checkedItemNum, setCheckedItemNum] = useState(0);
    const [allChecked, setAllChecked] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isUpdateModalOpen, setIsUpdateModalOpen] = useState(false);
    const [loading, setLoading] = useState(false);
    const [newTestName, setNewTestName] = useState('');
    const [newUpdateTestName, setUpdateTestName] = useState('');
    const [dateString,setDateString] = useState('');
    const [curPartId,setCurPartId] = useState('');


    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleAddTest = async () => {
        setLoading(true);
        console.log(newTestName);
        console.log(dateString);
        const res = await addPartAPI({
            "class_id": user_status.class_id,
            "partid": partList.length+1,
            "part_ddl": dateString,
            "key_word": newTestName
        }, user_status.token);
        console.log(res);
        setNewTestName('');
        message.success('添加成功');
        window.location.reload();
        setLoading(false);
        setIsModalOpen(false);
    };

    const handleSetDDL = (date, dateStr) => {
        setDateString(dateStr);
    };

    const handleCancelAddTest = () => {
        setIsModalOpen(false);
    };

    const showUpdateModal = (partid) => {
        setCurPartId(partid);
        setIsUpdateModalOpen(true);
    }

    const handleUpdateTest = async () => {
        setLoading(true);
        console.log(newTestName);
        console.log(dateString);
        const res = await changePartAPI({
            "class_id": user_status.class_id,
            "partid": curPartId,
            "part_ddl": dateString,
            "key_word": newTestName
        }, user_status.token);
        console.log(res);
        setNewTestName('');
        message.success('修改成功');
        window.location.reload();
        setLoading(false);
        setIsModalOpen(false);
        setIsUpdateModalOpen(false);
    }

    const handleUpdateDDL = (date, dateStr) => {
        setDateString(dateStr);
    }

    const handleCancelUpdateTest = () => {
        setIsUpdateModalOpen(false);
    }

    // 当组件渲染完成时执行一次
    useEffect(() => {

        const getTestList = async function () {
            dispatch(fetchGetPartList(user_status.class_id, user_status.token));

        }

        getTestList();
    }, [])

    useEffect(() => {
        if (partList.length !== 0) {
            setCheckList(Array(partList.length).fill(false));
            // console.log(checkList);
        }
    }, [partList]);

    useEffect(() => {
        if (checkList.length !== 0) {
            setHasChecked(checkList.reduce((a, b) => a || b), false);
            setCheckedItemNum(checkList.reduce((a, b) => b ? ++a : a, 0));
            setAllChecked(checkList.reduce((a, b) => a && b), true);
        }
    }, [checkList])


    const handleAllCheck = (e) => {
        setCheckList(checkList.map(() => e.target.checked))
    }

    const handleCancel = () => {
        setCheckList(checkList.map(() => false));
    }

    const handleDeletePart = async () => {
        setLoading(true);
        const res = await deletePartAPI({
            class_id:user_status.class_id,
            partid:curPartId
        },user_status.token); 
        console.log(res);
        window.location.reload();
        setLoading(false);
        setIsModalOpen(false);
        setIsUpdateModalOpen(false);
    }   


    return (
        <div className='TeacherTestList'>
            <nav
                style={{
                    height: hasChecked ? '40px' : '0'
                }}
            >
                <div className='all-check'>
                    <input
                        type='checkbox'
                        onChange={handleAllCheck}
                        checked={allChecked}
                        id='allcheckbox'
                    />
                    <label htmlFor='allcheckbox'>全选</label>
                    <div className='divide-line'></div>
                    <span>已选择{checkedItemNum}个习题</span>
                </div>
                <div className='delet-test'>
                    <button><DeleteOutlined /> 删除</button>
                    <div className='divide-line'></div>
                    <button onClick={handleCancel}>取消</button>
                </div>
            </nav>
            <main>
                {partList.length === 0 || partList.map(ele =>
                    <TestItem
                        key={ele.id}
                        info={ele}
                        ifChecked={checkList[ele.id]}
                        onCheck={(key) => {
                            setCheckList(checkList.map((ele, index) => index === key ? !ele : ele));
                        }}
                        showUpdateModal={showUpdateModal}
                    />
                )}
            </main>
            <ConfigProvider
                theme={{
                    token: {
                        // Seed Token，影响范围大
                        colorPrimary: '#2486b9',
                        borderRadius: 5,

                        // 派生变量，影响范围小
                        // colorBgContainer: '#f6ffed',
                    },
                }}
            >
                <Button
                    type="primary"
                    onClick={showModal}
                    className='add-test'
                >
                    <PlusOutlined />
                </Button>
                <Modal
                    title={<h3>新增测验</h3>}
                    open={isModalOpen}
                    onCancel={handleCancelAddTest}
                    footer={[
                        <Button key="back" onClick={handleCancelAddTest}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={handleAddTest}>
                            确定
                        </Button>
                    ]}
                    centered
                    width={480}
                >
                    <label htmlFor='newtestname'>请输入新增测验的关键词</label>
                    <Input id='newtestname' onInput={function (e) { setNewTestName(e.target.value) }} value={newTestName} />
                    <div>请选择测验的截止日期</div>
                    <DatePicker onChange={handleSetDDL} placeholder='截止日期' />
                </Modal>
                <Modal
                    title={<h3>修改测验信息</h3>}
                    open={isUpdateModalOpen}
                    onCancel={handleCancelUpdateTest}
                    footer={[
                        <Button danger onClick={handleDeletePart}>删除该章节</Button>,
                        <Button key="back" onClick={handleCancelUpdateTest}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={handleUpdateTest}>
                            确定
                        </Button>
                    ]}
                    centered
                    width={480}
                >
                    <label htmlFor='updatetestname'>请输入想要修改测验的关键词</label>
                    <Input id='updatetestname' onInput={function (e) { setUpdateTestName(e.target.value) }} value={newUpdateTestName} />
                    <div>请选择想要修改测验的截止日期</div>
                    <DatePicker onChange={handleUpdateDDL} placeholder='截止日期' />
                </Modal>
            </ConfigProvider>
        </div>
    )
}